package com.tang.nacos.config;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

/**
 * 自定义分库算法
 */
public class MyDatabaseShardingAlgorithm implements ComplexKeysShardingAlgorithm {

  @Override
  public Collection<String> doSharding(Collection collection,
      ComplexKeysShardingValue complexKeysShardingValue) {
    System.out.println("当前存在的库有:" + collection);
    Map columnNameAndShardingValuesMap = complexKeysShardingValue
        .getColumnNameAndShardingValuesMap();
    System.out.println("传入的参数列表:" + columnNameAndShardingValuesMap);
    //业务逻辑
    List idList = (List) columnNameAndShardingValuesMap.get("id");
    Long id = null;
    if (CollectionUtils.isNotEmpty(idList)) {
      id = (Long) idList.get(0);
    }
    List ageList = (List) columnNameAndShardingValuesMap.get("age");
    Integer age = null;
    if (CollectionUtils.isNotEmpty(ageList)) {
      age = (Integer) ageList.get(0);
    }
    if (Objects.nonNull(id)) {
      if (id % 2 == 0) {
        return Arrays.asList("ds1");
      } else {
        return Arrays.asList("ds0");
      }
    }
    if (Objects.nonNull(age)) {
      if (age % 2 == 0) {
        return Arrays.asList("ds1");
      } else {
        return Arrays.asList("ds0");
      }
    }
    return Arrays.asList("ds1", "ds0");
  }
}
